package com.javaex.book.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.javaex.book.annotation.Controller;
import com.javaex.book.annotation.RequestMapping;
import com.javaex.book.pojo.Book;
import com.javaex.book.pojo.Cart;
import com.javaex.book.pojo.CartItem;
import com.javaex.book.service.BookService;
import com.javaex.book.service.impl.BookServiceImpl;
import com.javaex.book.utils.Pages;
import com.javaex.book.utils.RequestMethod;
import com.javaex.book.utils.ReturnResult;
import com.javaex.book.utils.WebUtils;

@Controller("/cart")
public class CartController {
	
	private static final Logger logger = LoggerFactory.getLogger(CartController.class);
	BookService bookService = new BookServiceImpl();

	// 前往购物车页面
	@RequestMapping()
	public String toCart(HttpSession session) {
		// token用于防止表单重复提交
		String token = UUID.randomUUID().toString().replace("-", "");
		session.setAttribute("token", token);
		return Pages.CART;
	}
	
	// 添加商品
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(HttpServletRequest req, HttpServletResponse resp, HttpSession session) {
		Integer id = Integer.parseInt(req.getParameter("id"));
		Book book = bookService.queryBookById(id);
		CartItem cartItem = new CartItem(book.getId(), book.getName(), 1, book.getPrice());
		logger.info("添加商品到购物车：{}", cartItem);
		Cart cart = (Cart) session.getAttribute("cart");
		if (cart == null) {
			cart = new Cart();
			session.setAttribute("cart", cart);
		}
		cart.add(cartItem);
		session.setAttribute("lastName", cartItem.getName());
		return Pages.redirect("/");
	}
	
	// 删除商品
	@RequestMapping("/delete")
	public String delete(HttpServletRequest req, HttpSession session) {
		Integer id = Integer.parseInt(req.getParameter("id"));
		Cart cart = (Cart) session.getAttribute("cart");
		if (cart != null) {
			cart.delete(id);
		}
		logger.info("删除商品：id = {}", id);
		return Pages.redirect("/cart");
	}
	
	// 清空购物车
	@RequestMapping("/clear")
	public String clear(HttpSession session) {
		session.removeAttribute("lastName");
		Cart cart = (Cart) session.getAttribute("cart");
		if (cart != null) {
			cart.clear();
		}
		return Pages.redirect("/cart");
	}
	
	// 修改商品
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ReturnResult update(HttpServletRequest req, HttpSession session) {
		Integer id = WebUtils.getInteger(req, "id", 0);
		Integer count = WebUtils.getInteger(req, "count", 0);
		if (id == 0 || count == 0) {
			return new ReturnResult().fail(); 
		}
		logger.info("修改商品 id = {} 数量为：count = {}", id, count);
		Cart cart = (Cart) session.getAttribute("cart");
		if (cart != null) {
			cart.update(id, count);
		}
		return new ReturnResult().success();
	}
}
